const request = require('../modules/request')

class Web {
    constructor() {

    }

    /**
     * 用户同意授权，获取code
     * @param {*} scope 
     */
    async oauth2Authorize(redirect_uri, scope, state) {
        return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
    }

    /**
     * 通过code换取网页授权access_token
     * 
     * @param {*} code 
     */
    async snsOauth2AccessToken(code) {
        const uri = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appid}&secret=${this.appsecret}&code=${code}&grant_type=authorization_code`
        const res = await request.get(uri)
        return res
    }


    /**
     * 刷新access_token
     * 
     * @param {*} refresh_token 
     */
    async snsOauth2RefreshToken(refresh_token) {
        const uri = `https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${this.appid}&grant_type=refresh_token&refresh_token=${refresh_token}`
        const res = await request.get(uri)
        return res
    }

    /**
     * 拉取用户信息(需scope为 snsapi_userinfo)
     * 
     * @param {*} access_token 
     * @param {*} openid 
     * @param {*} lang 
     */
    async snsUserInfo(access_token, openid, lang = 'zh_CN') {
        const uri = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=${lang}`
        const res = await request.get(uri)
        return res
    }

    /**
     * 检验授权凭证
     * @param {*} access_token 
     * @param {*} openid 
     */
    async snsAuth(access_token, openid) {
        const uri = `https://api.weixin.qq.com/sns/auth?access_token=${access_token}&openid=${openid}`
        const res = await request.get(uri)
        return res
    }
}

module.exports = Web